<?php
$loader->requireOnce('includes/Icd10Selector/Icd10Selector.class.php');
$loader->requireOnce('includes/EmrErrorCode.class.php');
 
class C_OdontoStomatology extends Controller {
	
	const ENABLE_SECONDARY_ICD = true;
	const TTSKTT = 'Chưa phát hiện bệnh';
	const KNM = 'Bình thường';
	const DTTQ_STEPS = 9;
	
	private $icd10Selector;
	
	public function C_OdontoStomatology($template_mod = 'general') {
		parent::Controller();		
		$this->template_mod = $template_mod;
		$this->view->path = 'odonto_stomatology';
		
		$this->icd10Selector = new Icd10Selector();
		$this->logger = LoggerManager::getLogger('modules.General_Emr.C_OdontoStomatology');
		$this->assign('numberOfStep', C_OdontoStomatology::DTTQ_STEPS);
	}
	
	public function createMedicalProfile($recordId = 0, $data = array()) {
	    $this->logger->info('start createMedicalProfile[' . $recordId . ']');
	    if ($recordId == 0) {
	        return;
	    }
	    
	    $rhmOdontologistEmrObj = Celini::newOrdo('RhmOdontologistEmr');
	    $data = array('medical_record_id' => $recordId,
	    'start_date' => date('Y-m-d H:i:s'),
	    'ttsk_ha'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_td'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_btm'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_cml'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_bg'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_dut'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_btk'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_bp'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_tkn'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_bddt'=> C_OdontoStomatology::TTSKTT,
	    'ttsk_kcky'=> C_OdontoStomatology::TTSKTT,
	    'kham_ngoai_mat'=> C_OdontoStomatology::KNM
	    );
	    $rhmOdontologistEmrObj->setData($data);
	    $rhmOdontologistEmrObj->persist();	     
	    $rhmKhamTrongMiengObj = Celini::newOrdo('RhmKhamTrongMieng');
	    $rhmKhamTrongMiengObj->register4Profile($recordId);
	    
	    $this->logger->info('finish createMedicalProfile[' . $recordId . ']');   
	    
	}
	
    /**
     * Validate user-key-in ICD10 code
     * @param $icd10Code
     * @return validate result: array('errorCode' => ['OK'|'ERROR'], 'errorMess' => sth)
     */
    public function validateKeyInIcd10($icd10Code){
        $icd10Id =   ORDataObject::factory('Icd10')->getObjectbyCode($icd10Code)->getId();
        $result         =   array('error' => 0, 'icd10_name' => '');
        if($icd10Code != '' && $icd10Id == ''){
            $result['error'] = 1;            
        }
        else if($icd10Code != '' && $icd10Id != ''){
            $result['icd10_name']= Celini::newORDO('Icd10', $icd10Id)->getLocalizedText('name');
        }
        return $result;
    }
	
    public function getMedicalProfile($recordId = 0) {
        $this->logger->info('start getMedicalProfile[' . $recordId . ']');
        if ($recordId == 0) {
            return;
        }
        
        $rhmOdontologistEmrObj = Celini::newOrdo('RhmOdontologistEmr');
        $rhmOdontologistEmrObj->loadProfile($recordId);
        
        
        $this->logger->info('finish getMedicalProfile[' . $recordId . ']');
        return $rhmOdontologistEmrObj;
    }
	
	public function actionLoadOdontoStomatology() {
		$this->logger->info('Start acitonLoadOdontoStomatology');
		
		$recordId	=	$_GET['recordId'];		        
		$patientId = Celini::newORDO('MedicalRecord', $recordId)->get('patient_id');
		$rhmOdontologistEmrObj = Celini::newOrdo('RhmOdontologistEmr');
		$rhmOdontologistEmrObj->loadProfile($recordId);							
		
		$this->icd10Selector->initIcd10ForController($this, 11, 111); 
		$icd10_1  =   ORDataObject::factory('Icd10');
        $icd10_1->setup($rhmOdontologistEmrObj->get('icd10_chinh_id'));
        $icd10_2    =   ORDataObject::factory('Icd10');
        $icd10_2->setup($rhmOdontologistEmrObj->get('icd10_phu_id'));
        $this->assign_by_ref('sec1Icd10', $icd10_1);
        $this->assign_by_ref('sec2Icd10', $icd10_2);            
        $this->assign_by_ref('patient', Celini::newORDO('Patient', $patientId));
		$this->assign_by_ref('emr', $rhmOdontologistEmrObj);
		$this->assign('adultTeeth', $this->buildAdultTeeth($recordId));
		$this->assign('childTeeth', $this->buildChildTeeth($recordId));
				
		$doctorId = $rhmOdontologistEmrObj->get('doctor_id');
		$this->assign('doctorId', $doctorId);
		$this->assign('doctorName', Celini::newOrdo('Employee', $doctorId)->get('name'));
		$this->assign('recordId', $recordId);
		$this->logger->info('Finish acitonLoadOdontoStomatology');
		return $this->view->render('edit_odonto_stomatology.html');
		
	}
	
	public function actionEditOdontoStomatology() {
	    $this->logger->info('Start actionEditOdontoStomatology');
	    $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
        'result'=>'');
	    
	    $recordId  =   $_POST['recordId'];
	    $data = $_POST['profile'];
        $rhmOdontologistEmrObj = Celini::newOrdo('RhmOdontologistEmr');
        $rhmOdontologistEmrObj->loadProfile($recordId);
        if ($rhmOdontologistEmrObj->get_id() == 0 
        || $rhmOdontologistEmrObj->get_id() =='') {
            
            $result['error']['code'] = EmrErrorCode::ODON_EMR_PROFILE_NOT_FOUND;
            $result['error']['mess'] = EmrErrorCode::getErrorMess( EmrErrorCode::ODON_EMR_PROFILE_NOT_FOUND);
            $this->logger->error('Save medical profile[' . $recordId . '] failed. This profile not exist');        
            
        } else {   
            $data['icd10_chinh_code'] = trim($data['icd10_chinh_code']);
            $data['icd10_phu_code'] = trim($data['icd10_phu_code']);            
            $validatedIcd10Id = $this->validateKeyInIcd10($data['icd10_chinh_code']);        
            $validatedSndIcd10Id = $this->validateKeyInIcd10($data['icd10_phu_code']);
            $result['result']['chinh'] = $validatedIcd10Id;
            $result['result']['phu'] = $validatedSndIcd10Id;
            
            // error occur
            if($validatedIcd10Id['error'] == 1){
                $result['error']['code']    =   EmrErrorCode::WRONG_C_ICD10_CODE;
                $result['error']['mess']    =   EmrErrorCode::getErrorMess(EmrErrorCode::WRONG_C_ICD10_CODE);               
                
                return json_encode($result);
            }
            if($validatedSndIcd10Id['error'] == 1){
                $result['error']['code']    =   EmrErrorCode::WRONG_P_ICD10_CODE;
                $result['error']['mess']    =   EmrErrorCode::getErrorMess(EmrErrorCode::WRONG_P_ICD10_CODE);               
                    
                           
                return json_encode($result);
            }//
            
            $icd10ChinhId    =   ORDataObject::factory('Icd10')->getObjectbyCode($data['icd10_chinh_code'])->getId();
            $icd10PhuId    =   ORDataObject::factory('Icd10')->getObjectbyCode($data['icd10_phu_code'])->getId();
            $data['icd10_chinh_id'] = $icd10ChinhId;
            $data['icd10_phu_id'] = $icd10PhuId; 
            $rhmOdontologistEmrObj->setData($data);            
            $rhmOdontologistEmrObj->persist();
            $result['result']['id'] = $rhmOdontologistEmrObj->get_id();
        }         
	       
	    $this->logger->info('Start actionEditOdontoStomatology');
	    return json_encode($result);
	}
	
	public function actionSetToothBridgeAjax() {
	    $teethObj = Celini::newOrdo('RhmKhamTrongMieng');
        $teethObj->setToothBridge($_POST['teethId'], $_POST['value']);
	}
	
	public function actionSetToothStatusAjax() {			    
	    $teethObj = Celini::newOrdo('RhmKhamTrongMieng');
        $teethObj->setToothStatus($_POST['toothId'], $_POST['value']);	
	}
	
	public function actionSetNoteAjax() {
		$teethObj = Celini::newOrdo('RhmKhamTrongMieng');
		return $teethObj->setNote($_POST['toothId'], $_POST['note']);
	}
	
	private function buildAdultTeeth($recordId) {
	    
		$teethName = array('8', '7', '6', '5', '4', '3', '2', '1', '1', '2', '3', '4', '5', '6', '7', '8');
			
		$adultToothObj = Celini::newOrdo('RhmKhamTrongMieng');		
		$adultTeeth = $adultToothObj->getUpperAdultTeeth($recordId);		
		$html = "<ol id='upperTeethAdult' style='height: 53px; width: 481px; position: relative;'>";
		$toothIndex = 0;
		foreach($adultTeeth as $tooth) {
			$statusDivs = $this->parseDiv($tooth['status']);
			$html .= '<li id="' . $tooth['rhm_kham_trong_mieng_id'] . '" class="tooth upper tooth-bridge-' . $tooth['bridge'] . '-top" status="' . $tooth['status'] . '">
						<div id="status_' . $tooth['rhm_kham_trong_mieng_id'] . '" style="height: 30px; width: 30px; position: absolute; top: 12px;">' .
							$statusDivs .
						"</div>
						<span index='{$tooth['enum_tooth']}'>{$teethName[$toothIndex]}</span>
						<span class='tooth-note'>{$tooth['note']}</span>
						<div class='tool-bar'>
							<div class='tool-bar-content'>
								<div class='tooth-status-btn-clear' style='margin-right: 10px;'></div>								
								<div class='tooth-status-btn-0' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-1' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-2' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-3' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-4' style='margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-5' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-6' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-7' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-8' style='margin-right: 10px;'></div>
								<div class='note'>
									<textarea style='width: 100%; height: 50px;'></textarea>
									<div class='tooth-loading' style='display: none;'></div>
									<a href='javascript:saveNote({$tooth['rhm_kham_trong_mieng_id']})'>Lưu ghi chú</a>&nbsp;
									<a href='javascript:clearNote({$tooth['rhm_kham_trong_mieng_id']})'>Xoá ghi chú</a>
								</div>
							</div>
						</div>
					</li>";
			$toothIndex++;
		}
		$html .= "</ol>
			<ol id='lowerTeethAdult' style='height: 52px; width: 481px; position: relative;'>";
		$adultTeeth = $adultToothObj->getLowerAdultTeeth($recordId);
		$toothIndex = 0;
		foreach($adultTeeth as $tooth) {
			$statusDivs = $this->parseDiv($tooth['status']);
			$html .= '<li id="' . $tooth['rhm_kham_trong_mieng_id'] . '" class="tooth lower tooth-bridge-' . $tooth['bridge'] . '-bottom" status="' . $tooth['status'] . '">
						<div id="status_' . $tooth['rhm_kham_trong_mieng_id'] . '" style="height: 30px; width: 30px; position: absolute; top: 10px;">' .
							$statusDivs .
						"</div>
						<span index='{$tooth['enum_tooth']}'>{$teethName[$toothIndex]}</span>
						<span class='tooth-note'>{$tooth['note']}</span>
						<div class='tool-bar'>
							<div class='tool-bar-content'>
								<div class='tooth-status-btn-clear' style='margin-right: 10px;'></div>								
								<div class='tooth-status-btn-0' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-1' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-2' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-3' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-4' style='margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-5' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-6' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-7' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-8' style='margin-right: 10px;'></div>
								<div class='note'>
									<textarea style='width: 100%; height: 50px;'></textarea>
									<div class='tooth-loading' style='display: none;'></div>
									<a href='javascript:saveNote({$tooth['rhm_kham_trong_mieng_id']})'>Lưu ghi chú</a>&nbsp;
									<a href='javascript:clearNote({$tooth['rhm_kham_trong_mieng_id']})'>Xoá ghi chú</a>
								</div>
							</div>
						</div>
					</li>";
			$toothIndex++;
		}
		$html .= "</ol>";
		return $html;
	}
	
	private function buildChildTeeth($recordId) {
		$teethName = array('V', 'IV', 'III', 'II', 'I', 'I', 'II', 'III', 'IV', 'V');
		$childToothObj = Celini::newOrdo('RhmKhamTrongMieng');
		$childTeeth = $childToothObj->getUpperChildTeeth($recordId);
		$html = "<ol id='upperTeethChild' style='height: 53px; width: 481px; position: relative;'>";
		$toothIndex = 0;
		foreach($childTeeth as $tooth) {
			$statusDivs = $this->parseDiv($tooth['status']);
			$html .= '<li id="' . $tooth['rhm_kham_trong_mieng_id'] . '" class="tooth upper tooth-bridge-' . $tooth['bridge'] . '-top" style="width: 48px;" status="' . $tooth['status'] . '">
						<div id="status_' . $tooth['rhm_kham_trong_mieng_id'] . '" style="height: 30px; width: 48px; position: absolute; top: 12px;">' .
							$statusDivs .
						"</div>
						<span index='{$tooth['enum_tooth']}'>{$teethName[$toothIndex]}</span>
						<span class='tooth-note'>{$tooth['note']}</span>
						<div class='tool-bar'>
							<div class='tool-bar-content'>
								<div class='tooth-status-btn-clear' style='margin-right: 10px;'></div>								
								<div class='tooth-status-btn-0' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-1' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-2' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-3' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-4' style='margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-5' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-6' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-7' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-8' style='margin-right: 10px;'></div>
								<div class='note'>
									<textarea style='width: 100%; height: 50px;'></textarea>
									<div class='tooth-loading' style='display: none;'></div>
									<a href='javascript:saveNote({$tooth['rhm_kham_trong_mieng_id']})'>Lưu ghi chú</a>&nbsp;
									<a href='javascript:clearNote({$tooth['rhm_kham_trong_mieng_id']})'>Xoá ghi chú</a>
								</div>
							</div>
						</div>
					</li>";
			$toothIndex++;
		}
		$html .= "</ol>
			<ol id='lowerTeethChild' style='height: 52px; width: 481px; position: relative;'>";
		$childTeeth = $childToothObj->getLowerChildTeeth($recordId);
		$toothIndex = 0;
		foreach($childTeeth as $tooth) {
			$statusDivs = $this->parseDiv($tooth['status']);
			$html .= '<li id="' . $tooth['rhm_kham_trong_mieng_id'] . '" class="tooth lower tooth-bridge-' . $tooth['bridge'] . '-bottom" style="width: 48px;" status="' . $tooth['status'] . '">
						<div id="status_' . $tooth['rhm_kham_trong_mieng_id'] . '" style="height: 30px; width: 48px; position: absolute; top: 10px;">' .
							$statusDivs .
						"</div>
						<span index='{$tooth['enum_tooth']}'>{$teethName[$toothIndex]}</span>
						<span class='tooth-note'>{$tooth['note']}</span>
						<div class='tool-bar'>
							<div class='tool-bar-content'>
								<div class='tooth-status-btn-clear' style='margin-right: 10px;'></div>								
								<div class='tooth-status-btn-0' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-1' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-2' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-3' style='margin-right: 10px; margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-4' style='margin-bottom: 10px;'></div>
								<div class='tooth-status-btn-5' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-6' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-7' style='margin-right: 10px;'></div>
								<div class='tooth-status-btn-8' style='margin-right: 10px;'></div>
								<div class='note'>
									<textarea style='width: 100%; height: 50px;'></textarea>
									<div class='tooth-loading' style='display: none;'></div>
									<a href='javascript:saveNote({$tooth['rhm_kham_trong_mieng_id']})'>Lưu ghi chú</a>&nbsp;
									<a href='javascript:clearNote({$tooth['rhm_kham_trong_mieng_id']})'>Xoá ghi chú</a>
								</div>
							</div>
						</div>
					</li>";
			$toothIndex++;
		}
		$html .= "</ol>";
		return $html;
	}
	
	private function parseDiv($status) {
		$statusDiv = '';
		for ($i = 0, $length = strlen($status); $i < $length; $i++) {
			if ($status[$i] == 1) {
				$statusDiv .= '<div class="tooth-status tooth-status-' . $i . '"></div>';
			}
		}
		
		return $statusDiv;
	}
	
}
?>